package org.ezplatform.office.questionnaire.web.rest;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.ezplatform.cloud.api.component.popuser.PopUserScopeUtilService;
import org.ezplatform.cloud.api.system.role.RoleApiService;
import org.ezplatform.cloud.common.log.LogService;
import org.ezplatform.component.check.service.DataCheckService;
import org.ezplatform.component.permission.service.CmpPermissionService;
import org.ezplatform.component.permission.utils.CmpPermissionConstant;
import org.ezplatform.core.annotation.AppLog;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.exception.ValidationException;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.security.SecurityUtils;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.controller.BaseController;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.office.questionnaire.entity.Questionnaire;
import org.ezplatform.office.questionnaire.entity.QuestionnaireTopic;
import org.ezplatform.office.questionnaire.service.QuesCache;
import org.ezplatform.office.questionnaire.service.QuestionnaireAnswerService;
import org.ezplatform.office.questionnaire.service.QuestionnaireAnswerStatusService;
import org.ezplatform.office.questionnaire.service.QuestionnaireService;
import org.ezplatform.office.questionnaire.service.QuestionnaireTopicOptionsService;
import org.ezplatform.office.questionnaire.service.QuestionnaireTopicService;
import org.ezplatform.office.questionnaire.util.SendMsgUtils;
import org.ezplatform.util.DateUtils;
import org.ezplatform.util.GlobalConstant;
import org.ezplatform.util.JsonUtils;
import org.ezplatform.util.JwtUtils;
import org.ezplatform.util.RestClient;
import org.ezplatform.util.StringUtils;
import org.ezplatform.util.UuidUtils;
import org.ezplatform.util.ValidateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
@RequestMapping(value = "/api/w/questionnaire/questionnaire")
public class QuestionnaireWebApiController extends BaseController<Questionnaire, String>{
	
	private final static Logger LOGGER = LoggerFactory.getLogger(QuestionnaireWebApiController.class);
	
	@Autowired
	private QuestionnaireService questionnaireService;
	
	@Autowired
	private PopUserScopeUtilService popUserUtilService;
	
	@Autowired
	private QuestionnaireAnswerService answerService;
	
	@Autowired
	private QuestionnaireAnswerStatusService answerStatusService;
	
	@Autowired
	private QuestionnaireTopicOptionsService optionService;
	
	@Autowired
	private QuestionnaireTopicService topicService;
	
	@Autowired
	private RoleApiService roleApiService;
	
	@Autowired
	private SendMsgUtils sendMsgUtils;
	
	@Autowired
	private LogService logService;
	
	@Autowired
	private DataCheckService dataCheckService;
	
    @Autowired
   	private CmpPermissionService cmpPermissionService;
    
    @Autowired
	private QuesCache quesCache;
	
	org.ezplatform.util.RestClient restClient = new org.ezplatform.util.RestClient(true);
	
	@Override
	protected BaseService<Questionnaire, String> getEntityService() {
		return questionnaireService;
	}
	
	  /**
     * 初始化数据
     * 
     * @param request
     * @param model
     * @param id
     */
    @ModelAttribute
    public void prepareModel(HttpServletRequest request, Model model,
            @RequestParam(value = "id", required = false) String id) {
        super.initPrepareModel(request, model, id);
    }
    
    /**
     * 判断实体是否存在
     * @param id
     * @return
     */
    @RequestMapping(value = "/entityIsExist", method = RequestMethod.POST)
    @ResponseBody
	public OperationResult entityIsExist(String id) {
    	Questionnaire entity = this.questionnaireService.findOne(id);
		if(entity == null) return OperationResult.buildSuccessResult("notExist");
		else return OperationResult.buildSuccessResult("exist");
	}
    
    /**
     * 获取列表（翻页）数据
     * 
     * @param request
     * @return json
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @RequiresPermissions("stdQuestionnaire:manage:03")
    @ResponseBody
    public Page<Map> findByPage(HttpServletRequest request) {
    	WebUser user = WebUtils.getCurrentUser();
    	String corpId = WebUtils.getCurrentUser().getCorpId();
    	List<Map> userL=questionnaireService.findByListNativeQuery("select user_status as userStatus,is_delete as isDelete from sys_user where id='"+user.getUserId()+"'", "");
		if(userL!=null && userL.size()>0) {
			Map userStatus=userL.get(0);
			if("offDuty".equals(userStatus.get("userStatus"))||"1".equals(userStatus.get("isDelete")+"")) {
				return new PageImpl<Map>(new ArrayList<Map>());
			}
		}
		
    	Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
		List<PropertyFilter> propertyFilter = PropertyFilter.buildFiltersFromHttpRequest(Questionnaire.class,request);
		Map<String,Object> paramMap = new HashMap<String,Object>();
		String sql ="SELECT oq.createdBy id, oq.id as dataId, oq.name, oq.type as type, oq.start_date AS startDate, oq.end_date AS endDate,oq.createdDate, oq.status,oq.publish,t.quesId,oq.close_date "
				+ "FROM oa_questionnaire oq LEFT JOIN (select oqa.questionnaire_id quesId from oa_questionnaire_answer oqa GROUP BY questionnaire_id) t on t.quesId=oq.ID WHERE oq.corp_id = :corpId ";
		//不是管理员，只能看自己创建的问卷  start
	
		List<Map<String, Object>> roleList = roleApiService.getRolesByUserId(user.getUserId(), corpId, TOKEN);
		boolean result = false;
		if (!roleList.isEmpty()) {
			String roleCode = "";
			for (Map<String, Object> map : roleList) {
				roleCode = StringUtils.null2String(map.get("roleCode"));
				if("appAdminRole".equals(roleCode)){
					result = true;
					break;
				}
			}
		}else if("admin".equals(user.getUserName())) {
			result = true;
		}
		if(!result){
			sql += " and oq.createdBy = :createdBy ";
			paramMap.put("createdBy", user.getUserId());
		}
		//不是管理员，只能看自己创建的问卷  end
		String publish = request.getParameter("publish");
		if(StringUtils.isNotBlank(publish)){
			if(!ValidateUtils.validateInt(publish)) {
				throw new ValidationException("非法参数");
			}
			sql += " and oq.publish = :publish ";
			paramMap.put("publish", publish);
		}
		// 截止时间开始
		String startTime = request.getParameter("startTime");
		if(StringUtils.isNotBlank(startTime)){
			sql += " and oq.close_date >= fn_str_to_date(:startTime, 'yyyy-MM-dd HH:mm:ss')";
			paramMap.put("startTime", startTime + " 00:00:00");
		}
		// 截止时间结束
		String endTime = request.getParameter("endTime");
		if(StringUtils.isNotBlank(endTime)){
			sql += " and oq.close_date <= fn_str_to_date(:endTime, 'yyyy-MM-dd HH:mm:ss')";
			paramMap.put("endTime", endTime + " 23:59:59");
		}
		paramMap.put("corpId", corpId);
		sql = PropertyFilter.getSqlByFilterAndPageable("oq",sql,"oq.createdDate desc", propertyFilter,pageable);
		Page<Map> page = questionnaireService.findByPageNativeSQL(pageable, sql,paramMap);
		Map<String, String> permissionInfoMap = new HashMap<String, String>();
		// map格式：key-权限编码，value-操作标识
		permissionInfoMap.put("stdQuestionnaire:manage:02", CmpPermissionConstant.PERMISSION_NAME_CAN_EDIT);
		permissionInfoMap.put("stdQuestionnaire:manage:04", CmpPermissionConstant.PERMISSION_NAME_CAN_DELETE);
		cmpPermissionService.processBaseListByDataScope(page.getContent(), user, permissionInfoMap, "user");
		for(Map<String,Object> ques:page.getContent()) {
			ques.put("id", ques.get("dataId"));
		}
		return page;
    }
    
    /**
     * 获取答卷统计列表（翻页）数据
     * 
     * @param request
     * @return json
     */
    @RequestMapping(value = "/statisticsList", method = RequestMethod.GET)
    @RequiresPermissions("stdQuestionnaire:answer:03")
    @ResponseBody
    public Page<Map> statisticsList(HttpServletRequest request) {
		WebUser user = WebUtils.getCurrentUser();
		Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
		List<PropertyFilter> propertyFilter = PropertyFilter.buildFiltersFromHttpRequest(Questionnaire.class,request);
		boolean isSuperAdmin = SecurityUtils.isSuperAdmin(WebUtils.getCurrentUser().getUserName());
		String publish = request.getParameter("publish");
		if(StringUtils.isNotBlank(publish) && !ValidateUtils.validateInt(publish)) {
			throw new ValidationException("非法参数");
		}
		return questionnaireService.getStaticList(isSuperAdmin,publish,user.getUserId(),user.getCorpId(),user.getJwtToken(),pageable,propertyFilter);
    }
    
    /**
     * 获取问卷类型分类
     * 
     * @param request
     * @return json
     */
    @SuppressWarnings("static-access")
	@RequestMapping(value = "/type", method = RequestMethod.GET)
    @ResponseBody
    public OperationResult getSource(HttpServletRequest request) {
    	Map<String,Object> map = new HashMap<String,Object>();
    	Questionnaire oq = new Questionnaire();
    	map.put("entity", oq);
    	WebUser user = WebUtils.getCurrentUser();
    	//将枚举去除
    	List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		Map<String,Object> typeMap = new HashMap<String,Object>();
		typeMap.put("questionnaireVote", "投票");
		typeMap.put("questionnaireSurvey", "调查");
    	map.put("types", list);
    	map.put("createdBy",user.getCnName());
    	String userJson = "[{\"scopeName\":\""+ user.getCnName() + "\",\"scopeType\":\"user\",\"scopeValue\":\"" + user.getUserId() + "\"}]";
    	map.put("userJson", userJson);
    	String jwtToken = user.getJwtToken();
		/*
		 * 1-启用(默认不选中) 2-启用(默认选中) 0-禁用
		 */
    	String evoRemindType=sendMsgUtils.getSysImType(user.getCorpId(), jwtToken,"evoRemind");
    	/*
    	 * 应用中心配置
    	 */
    	Map<String,Object>appInfo=sendMsgUtils.getAppInfoByAppCode(user.getCorpId(), jwtToken);
    	String reminderAction="";
    	if(MapUtils.isNotEmpty(appInfo)) {
	          reminderAction = StringUtils.null2String(appInfo.get("reminderAction"));
	    }
		/*
		 * wxWork - 企业微信，ding - 钉钉 ，evoPortal - evoPortal， CoCall- CoCall
		 */
    	String sysNoticeType = sendMsgUtils.getSysImType(user.getCorpId(), jwtToken,"sysImType");//后台是否开启提醒（管理后台）
    	/*
		 * 1-启用(默认不选中) 2-启用(默认选中) 0-禁用
		 */
    	String sysSmsType = sendMsgUtils.getSysImType(user.getCorpId(), jwtToken, "sysSMSsetting");//获取短信后台是否开启
    	Map<String,Object> remindConfig=new HashMap<String,Object>();
    	evoRemindType=StringUtils.isBlank(evoRemindType)?"0":evoRemindType;
    	remindConfig.put("w_mobile", evoRemindType);
    	sysNoticeType=","+sysNoticeType+",";
    	if(StringUtils.contains(sysNoticeType, ",evoPortal,")||StringUtils.contains(sysNoticeType, ",wxWork,")
    			||StringUtils.contains(sysNoticeType, ",ding,")||StringUtils.contains(sysNoticeType, ",CoCall,")) {
    		if(reminderAction.contains("mobile")) {
    			remindConfig.put("w_webapp", true);
    		}else remindConfig.put("w_webapp", false);
    		
    	}
    	sysSmsType=StringUtils.isBlank(sysSmsType)?"0":sysSmsType;
    	if(!reminderAction.contains("sms")) {
    		sysSmsType="0";
    	}
    	remindConfig.put("w_sms", sysSmsType);
    	map.put("remindConfig",remindConfig);
    	return OperationResult.buildSuccessResult(map);
    }
    
    /**
     * 编辑/新建
     * @param request
     * @return json
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    @ResponseBody
    public OperationResult edit(HttpServletRequest request,@RequestParam("id") String id) {
		if (!this.dataCheckService.checkCustom(id, "oa_questionnaire", "id", "publish", "0")
				&& !this.dataCheckService.checkCustom(id, "oa_questionnaire", "id", "publish", "2")) {
			throw new ValidationException("没有操作权限");
		}
		
    	Map<String, Object> map = new HashMap<>();
    	WebUser user = WebUtils.getCurrentUser();
    	String userId = user.getUserId();
    	String token = user.getJwtToken();
    	Map<String,Object> oq = questionnaireService.getQuesById(id);

    	/*
    	 * 获取问卷题目的集合
    	 */
    	List<QuestionnaireTopic> questionnaireTopicList = topicService.getTopicOPtionInfo(id,userId,token,false);
    	/*
    	 * 当问卷设计过题目后，就不能在编辑问卷类型
    	 */
    	if(questionnaireTopicList == null || questionnaireTopicList.size() == 0) {
    		map.put("typeAble", false);
    	}else {
    		map.put("typeAble", true);
    	}
    	map.put("entity", oq);
    	String questionnaireScope =popUserUtilService.getScopeTypeValue("oa_questionnaire_scope","oa_questionnaire", "questionnaire_scope",StringUtils.null2String(oq.get("questionnaire_scope")));
    	//剔除钉钉在系统中没有账号的人   答卷人
		String qScope = "";
		if(StringUtils.isNotBlank(questionnaireScope)){
			String[] qScopeArr = questionnaireScope.split(",");
			for (String s : qScopeArr) {
				if(s.indexOf("null") < 0) {
					qScope += s + ",";
				}
			}
			if(StringUtils.isNotBlank(qScope)){
				qScope = qScope.substring(0,qScope.length() - 1);
			}
		}
    	String answerScope =popUserUtilService.getScopeTypeValue("oa_questionnaire_scope","oa_questionnaire", "answer_scope",StringUtils.null2String(oq.get("answer_scope")));
    	//剔除钉钉在系统中没有账号的人   查看答案人
		String aScope = "";
		if(StringUtils.isNotBlank(answerScope)){
			String[] aScopeArr = answerScope.split(",");
			for (String s : aScopeArr) {
				if(s.indexOf("null") < 0) {
					aScope += s + ",";
				}
			}
			if(StringUtils.isNotBlank(aScope)){
				aScope = aScope.substring(0,aScope.length() - 1);
			}
		}
    	map.put("entity", oq);
    	map.put("questionnaireScope", qScope);
    	map.put("answerScope", aScope);
    	//将枚举去除
    	List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		Map<String,Object> typeMap = new HashMap<String,Object>();
		typeMap.put("questionnaireVote", "投票");
		typeMap.put("questionnaireSurvey", "调查");
    	map.put("types", list);
		map.put("createdBy",StringUtils.null2String(oq.get("user_name")));
		Map<String,Object> msg=new HashMap<String,Object>(1);
		msg.put("i18NCode", "oa.que.savesuccess");
		map.putAll(msg);
		String jwtToken = user.getJwtToken();
		/*
		 * 1-启用(默认不选中) 2-启用(默认选中) 0-禁用
		 */
    	String evoRemindType=sendMsgUtils.getSysImType(user.getCorpId(), jwtToken,"evoRemind");
    	/*
    	 * 应用中心配置
    	 */
    	Map<String,Object>appInfo=sendMsgUtils.getAppInfoByAppCode(user.getCorpId(), jwtToken);
    	String reminderAction="";
    	if(MapUtils.isNotEmpty(appInfo)) {
	          reminderAction = StringUtils.null2String(appInfo.get("reminderAction"));
	    }
    	/*
		 * wxWork - 企业微信，ding - 钉钉 ，evoPortal - evoPortal， CoCall- CoCall
		 */
    	String sysNoticeType = sendMsgUtils.getSysImType(user.getCorpId(), jwtToken,"sysImType");//后台是否开启提醒（管理后台）
    	/*
		 * 1-启用(默认不选中) 2-启用(默认选中) 0-禁用
		 */
    	String sysSmsType = sendMsgUtils.getSysImType(user.getCorpId(), jwtToken, "sysSMSsetting");//获取短信后台是否开启
    	Map<String,Object> remindConfig=new HashMap<String,Object>();
    	evoRemindType=StringUtils.isBlank(evoRemindType)?"0":evoRemindType;
    	remindConfig.put("w_mobile", evoRemindType);
    	sysNoticeType=","+sysNoticeType+",";
    	if(StringUtils.contains(sysNoticeType, ",evoPortal,")||StringUtils.contains(sysNoticeType, ",wxWork,")
    			||StringUtils.contains(sysNoticeType, ",ding,")||StringUtils.contains(sysNoticeType, ",CoCall,")) {
    		if(reminderAction.contains("mobile")) {
    			remindConfig.put("w_webapp", true);
    		}else remindConfig.put("w_webapp", false);
    	}
    	
    	sysSmsType=StringUtils.isBlank(sysSmsType)?"0":sysSmsType;
    	if(!reminderAction.contains("sms")) {
    		sysSmsType="0";
    	}
    	remindConfig.put("w_sms", sysSmsType);
    	map.put("remindConfig",remindConfig);
		return OperationResult.buildSuccessResult(map);
    }
    
    /**
     * 查看
     * @param request
     * @return json
     */
    @RequestMapping(value = "/view", method = RequestMethod.GET)
    @ResponseBody
    public OperationResult view(@RequestParam("id") String id, HttpServletRequest request) {
    	Map<String, Object> map = new HashMap<String, Object>();
    	Map<String,Object> cmap = new HashMap<String, Object>();
    	WebUser user = WebUtils.getCurrentUser();
		Map<String,Object> oq = questionnaireService.getQuesById(id);
    	map.put("entity", oq);
    	String questionnaireScope = questionnaireService.getscopeName("oa_questionnaire", StringUtils.null2String(oq.get("questionnaireScope")), "questionnaire_scope");
    	String answerScope = questionnaireService.getscopeName("oa_questionnaire", StringUtils.null2String(oq.get("answerScope")), "answer_scope");
    	cmap.put("questionnaireScope", questionnaireScope);
    	cmap.put("answerScope", answerScope);
    	map.put("views", cmap);
    	map.put("createdBy",StringUtils.null2String(oq.get("user_name")));
    	// 日志启用标记
    	boolean optLogFlag = this.logService.checkOptLog(user.getCorpId(), "questionnaireLog:manage:03", TOKEN);
    	if (optLogFlag) {
    		//记录日志
            this.logService.saveModuleLog("questionnaireLog:manage:03", (String)oq.get("name"), "");
    	}
    	return OperationResult.buildSuccessResult(map);
    }
    
    /**
     * 保存问卷
     * @param entity
     * @param model
     * @return
     * @throws ParseException 
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    public OperationResult save(@ModelAttribute("entity") Questionnaire entity, HttpServletRequest request) throws ParseException {
    	WebUser user = WebUtils.getCurrentUser();
    	String corpId = user.getCorpId();
    	String id = entity.getId();
    	String oldName = "";
    	Map<String,Object> msg=new HashMap<String,Object>(1);
    	if(StringUtils.isNotEmpty(id)) {
    		Questionnaire qu = this.questionnaireService.findOne(id);
    		oldName = qu.getName();
    	}
    	boolean flag = questionnaireService.checkName(entity.getId(), entity.getName(), corpId);
    	if(flag){
    		msg.put("i18NCode", "oa.que.inputanswernamexist");
    		return OperationResult.buildFailureResult("您输入的问卷名称已存在",msg);
    	}
    	boolean checkName = entity.getName().contains("<script>");
    	if(checkName) {
    		return OperationResult.buildFailureResult("非法参数，禁止输入");
    	}
    	if(StringUtils.isNotEmpty(entity.getDescription())) {
    		boolean checkDescription = entity.getDescription().contains("<script>");
    		if(checkDescription) {
    			return OperationResult.buildFailureResult("非法参数，禁止输入");
    		}
    	}
    	if(entity.getPublish()==Questionnaire.PublishEnum.DIES_VENIT.getCode()) {
    		entity.setPublish(Questionnaire.PublishEnum.NOPUBLISH.getCode());
    	}
    	String jsonStrQuestionnaireScope = StringUtils.null2String(request.getParameter("jsonStrQuestionnaireScope"));
    	String jsonStrAnswerScope = StringUtils.null2String(request.getParameter("jsonStrAnswerScope"));
    	String quesScope = entity.getQuestionnaireScope();
    	
    	/**
    	 * 根据适用范围  获取总应答题人数
    	 */
    	if(StringUtils.isEmpty(jsonStrQuestionnaireScope) || "[]".equals(jsonStrQuestionnaireScope)) {
    		List<Map> list = questionnaireService.getAllUser(corpId);
        	entity.setAllUserNum(list.size());
    	}else {
    		Set<String> set = questionnaireService.getAllUserNum(jsonStrQuestionnaireScope, corpId, user.getJwtToken()); 
        	entity.setAllUserNum(set.size());
    	}
    	
    	if(!"".equals(jsonStrQuestionnaireScope)){
    		if("".equals(StringUtils.null2String(quesScope))){
    			quesScope = UuidUtils.UUID();
    			entity.setQuestionnaireScope(quesScope);
    		}
    		this.popUserUtilService.saveScopeData("oa_questionnaire_scope", quesScope, jsonStrQuestionnaireScope, "oa_questionnaire","questionnaire_scope");
    	}else{
    		if(quesScope!=null) {
    			this.popUserUtilService.delScopeMethod("oa_questionnaire_scope",quesScope,"oa_questionnaire","questionnaire_scope");
    		}
    		entity.setQuestionnaireScope(null);
    	}
    	
    	String answerScope = entity.getAnswerScope();
    	if(!"".equals(jsonStrAnswerScope)){
    		if("".equals(StringUtils.null2String(answerScope))){
    			answerScope = UuidUtils.UUID();
    			entity.setAnswerScope(answerScope);
    		}
    		this.popUserUtilService.saveScopeData("oa_questionnaire_scope",answerScope , jsonStrAnswerScope, "oa_questionnaire","answer_scope");
    	}else{
    		this.popUserUtilService.delScopeMethod("oa_questionnaire_scope",answerScope,"oa_questionnaire","answer_scope");
    		entity.setAnswerScope(null);
    	}
    	
    	String closeDate = StringUtils.null2String(request.getParameter("closeDate"));
    	if (StringUtils.isNotBlank(closeDate)) {
    		entity.setCloseDate(DateUtils.parseTime(closeDate));
    	}
    	String publishDate = StringUtils.null2String(request.getParameter("publishDate"));
    	if (StringUtils.isNotBlank(publishDate) && entity.getIsTimingPublish() == 1) {
    		entity.setPublishDate(DateUtils.parseTime(publishDate));
    	} else {
    		entity.setPublishDate(null);
    	}
    	
    	entity.setStatus("2");
    	entity.setSendStatus(Questionnaire.SendStatusEnum.NOSEND.getCode());
    	OperationResult result = super.editSave(entity);
		if("0".equals(result.getCode())) {
			//记录日志
	  		if(StringUtils.isNotEmpty(id)) {
	  		    // 日志启用标记
		    	boolean optLogFlag = this.logService.checkOptLog(corpId, "questionnaireLog:manage:02", TOKEN);
		    	if (optLogFlag) {
		    		this.logService.saveModuleLog("questionnaireLog:manage:02", oldName, "");
		    	}
	  		} else {
	  		    // 日志启用标记
		    	boolean optLogFlag = this.logService.checkOptLog(corpId, "questionnaireLog:manage:01", TOKEN);
		    	if (optLogFlag) {
		    		this.logService.saveModuleLog("questionnaireLog:manage:01", entity.getName(), "");
		    	}
	  		} 
		}
		msg.put("i18NCode", "oa.que.savesuccess");
    	return OperationResult.buildSuccessResult("保存成功",msg);
    }
    
    /**
     * 编辑/新建
     * @param request
     * @return json
     */
    @RequestMapping(value = "/titleEdit", method = RequestMethod.GET)
    @ResponseBody
    public OperationResult titleEdit(@RequestParam("id") String id) {
    	Map<String, Object> map = new HashMap<String, Object>();
    	Questionnaire oq = this.questionnaireService.findOne(StringUtils.null2String(id));
    	String titleSetting = oq.getTitleSetting();
    	if(!"".equals(StringUtils.null2String(titleSetting))){
    		Map<String, Object> mapSetting = new HashMap<String, Object>();
        	mapSetting = JsonUtils.readValue(titleSetting);
        	map.put("titleSetting", mapSetting);
    	}else{
    		Map<String, Object> mapSetting = new HashMap<String, Object>();
    		mapSetting.put("tFontFamily", "微软雅黑");
    		mapSetting.put("tFontSize", "24px");
    		mapSetting.put("bold", "");
    		mapSetting.put("italic", "");
    		mapSetting.put("underline", "");
    		mapSetting.put("ezQuesColor", "");
    		map.put("titleSetting", mapSetting);
    	}
    	map.put("entity", oq);
    	return OperationResult.buildSuccessResult(map);
    }
    
    
    /**
     * 保存问卷
     * @param entity
     * @param model
     * @return
     */
    @RequestMapping(value = "/titleEdit", method = RequestMethod.POST)
    @ResponseBody
    public OperationResult titleEdit(@ModelAttribute("entity") Questionnaire entity,HttpServletRequest request) {
    	WebUser user = WebUtils.getCurrentUser();
    	String corpId = user.getCorpId();
    	/*问卷标题*/
    	String title = StringUtils.null2String(request.getParameter("title"));
    	/*标题设置*/
    	String titleSetting = StringUtils.null2String(request.getParameter("titleSetting"));
    	/*问卷描述*/
    	String titleDescription =StringUtils.null2String(request.getParameter("titleDescription"));
    	String titleDescriptionTxt =StringUtils.null2String(request.getParameter("titleDescriptionHid"));
    	boolean flag = questionnaireService.checkName(entity.getId(), title, corpId);
    	Map msg=new HashMap(1);
    	if(flag){
    		msg.put("i18NCode", "oa.que.inputanswernamexist");
    		return OperationResult.buildFailureResult("您输入的问卷名称已存在",msg);
    	}
    	entity.setName(title);
    	entity.setTitle(title);
    	entity.setTitleDescription(titleDescription);
    	entity.setTitleDescriptionTxt(titleDescriptionTxt);
    	entity.setTitleSetting(titleSetting);
    	return super.editSave(entity);
    }
    
    
    /**
     * 修改问卷状态
     * @param id
     * @param status
     * @return
     */
    @RequestMapping(value = "/setStatus", method = RequestMethod.POST)
    @ResponseBody
    public OperationResult setStatus(HttpServletRequest request,@RequestParam("id") String id,@RequestParam("status") String status) {
    	WebUser user = WebUtils.getCurrentUser();
    	Map i18nKey=new HashMap();
		Integer flag = questionnaireService.updateQuStatus(id,user.getUserId(),user.getCorpId(),user.getJwtToken(),request);
		if(StringUtils.equals(flag.toString(),Questionnaire.StatusEnum.OPEN.getCode())){
			OperationResult.buildFailureResult("问卷已经开启",1);
		}

    	/*status：0是关闭、1是开启、2是未开启；状态流转，2未开启到1开启，1开启到0关闭，0关闭到1开启*/
    	if("0".equals(status)||"2".equals(status)) {
    		List<QuestionnaireTopic> list = topicService.getTopicOPtionInfo(id,WebUtils.getCurrentUser().getUserId(),user.getJwtToken(),true);
    		int length = list.size();
    		if(length==0) {
    			i18nKey.put("i18NCode", "oa.que.cannotstarted");
    			return OperationResult.buildFailureResult("未添加题目的问卷不能开启",i18nKey);
    		}
    	}
    	Questionnaire oq = questionnaireService.findOne(id);
    	Date date = new Date();
		Date endDate = oq.getEndDate();
    	if("2".equals(status)){
    		oq.setStatus("1");
    		oq.setStartDate(date);

    		if(endDate.getTime() < date.getTime()){
    			i18nKey.put("i18NCode", "oa.que.endtimegtcurtime");
				return OperationResult.buildFailureResult("问卷结束时间应大于当前时间",i18nKey);
			}
			questionnaireService.sendThreadQues(id,user.getUserId(),user.getCorpId(),user.getJwtToken(),request);
			questionnaireService.setQuesSendY(id);
    	}else if("0".equals(status)){
    		if(endDate.getTime()<date.getTime()){
    			i18nKey.put("i18NCode", "oa.que.endtimegtcurtime");
    			return OperationResult.buildFailureResult("问卷结束时间应大于当前时间",i18nKey);
    		}
    		oq.setStatus("1");
    		oq.setStartDate(date);
			questionnaireService.sendThreadQues(id,user.getUserId(),user.getCorpId(),user.getJwtToken(),request);
			questionnaireService.setQuesSendY(id);
    	}else if("1".equals(status)){
    		oq.setStatus("0");
    		oq.setEndDate(date);
    		questionnaireService.setQuesSendN(id);
    		answerStatusService.updateStatusToSubmit(id);
    	}
    	return this.editSave(oq);
    }
    
    /**
	 * 逻辑删除
	 * @param entity
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	@AppLog
	public OperationResult delete(HttpServletRequest request,Model model, @RequestParam("ids") String... ids) {
		/*List<String> idList = Arrays.asList(ids);
		if (!this.dataCheckService.checkCustom(idList, "oa_questionnaire", "id", "publish", "0")
				&& !this.dataCheckService.checkCustom(idList, "oa_questionnaire", "id", "publish", "2")) {
			return OperationResult.buildFailureResult("没有操作权限");
		}*/
		WebUser user = WebUtils.getCurrentUser();
		String corpId = user.getCorpId();
		List<Questionnaire> questionnaireList = questionnaireService.findAll(ids);
		Map<String,Integer> idPublishMap = questionnaireList.stream().collect(Collectors.toMap(Questionnaire::getId,Questionnaire::getPublish));
		//保存需要删除的问卷id
		List<String> list = new ArrayList<>();
		Map i18nKey=new HashMap();
		for (Map.Entry<String, Integer> entry : idPublishMap.entrySet()) {
			if(entry.getValue().intValue() == Questionnaire.PublishEnum.PUBLISH.getCode()){
				if(ids.length == 1){
					i18nKey.put("i18NCode", "oa.que.answerpublished");
					return OperationResult.buildFailureResult("该问卷已经发布",i18nKey);
				}
			}else{
				list.add(entry.getKey());
			}
		}
		if(CollectionUtils.isEmpty(list)) {
			i18nKey.put("i18NCode", "oa.que.deletesuccessful");
			OperationResult.buildSuccessResult("删除成功",i18nKey);
		}
		//查询问卷题目
		List<String> topicList = topicService.getTopicIdByQeusId(list);
		//删除答卷
		if(topicList != null && topicList.size() >0){
			answerStatusService.deleteStatusByQuesId(list);
			answerService.deleteAnswerByQuesId(list);
			//删除问卷选项
			optionService.deleteOptionsByTopicId(topicList);
			topicService.deleteTopicByQuesId(list);
		}
		List<String> quesScopeList = questionnaireService.getQuesScopeById(list);
		List<String> answerScopeList = questionnaireService.getAnswerScopeById(list);
		popUserUtilService.delScopeMethod("oa_questionnaire_scope", quesScopeList, "oa_questionnaire", "questionnaire_scope");
		popUserUtilService.delScopeMethod("oa_questionnaire_scope", answerScopeList, "oa_questionnaire", "answer_scope");
		
		sendMsgUtils.deleteMessage(Arrays.asList(ids), corpId, TOKEN);
		OperationResult result = super.delete(ids);
		if("0".equals(result.getCode())) {
			boolean optLogFlag = this.logService.checkOptLog(corpId, "questionnaireLog:manage:04", TOKEN);
	    	//记录日志
	    	if(optLogFlag && CollectionUtils.isNotEmpty(questionnaireList)) {
	    		List<Map<String, String>> operateDataList = new ArrayList<>();
	    		for(Questionnaire qu : questionnaireList) {
	    			Map<String, String> operateDataMap = new HashMap<>();
	    			// 操作数据
	    			operateDataMap.put("operateData", qu.getName());
	    			// 操作明细
	    			operateDataMap.put("operateDetails", "");
	    			// 请求Id
	    			operateDataMap.put("requestId", null);
	    			operateDataList.add(operateDataMap);
	    		}
	    		// 记录批量日志
	    		this.logService.batchSaveModuleLog("questionnaireLog:manage:04", operateDataList, request);
	    	}
		}
		return result;
	}
	
	/**
     * 获取问卷类型分类
     * 
     * @param request
     * @return json
     */
    @RequestMapping(value = "/scopeValue", method = RequestMethod.GET)
    @ResponseBody
    public OperationResult getScopeValue(HttpServletRequest request) {
    	Map<String,Object> map = new HashMap<String,Object>();
    	String questionnaireScope = UuidUtils.UUID();
    	String answerScope = UuidUtils.UUID();
    	map.put("questionnaireScope", questionnaireScope);
    	map.put("answerScope", answerScope);
    	return OperationResult.buildSuccessResult(map);
    }


	/**
	 * 检查 问卷状态  并且修改状态
	 * @param request
	 * @return
	 */
	@GetMapping("/checkQuesStatus")
	@ResponseBody
    public OperationResult checkQuesStatus(HttpServletRequest request){
		WebUser user = WebUtils.getCurrentUser();
		Map<String,Object> map = new HashMap<String,Object>();
		String quesId = request.getParameter("id");
		if(quesId != null && !ValidateUtils.validateId(quesId)) {
            throw new ValidationException("非法参数");
        }
		int flag = questionnaireService.updateQuStatus(quesId,user.getUserId(),user.getCorpId(),user.getJwtToken(),request);
		map.put("status",flag);
		return OperationResult.buildSuccessResult(map);
	}


	/**
	 * 发布问卷/关闭问卷
	 * @return
	 */
	@GetMapping("/publish")
	@ResponseBody
	public OperationResult publish(HttpServletRequest request){
		Map i18nKey=new HashMap();
		String id = request.getParameter("id");
		if(id != null && !ValidateUtils.validateId(id)) {
            throw new ValidationException("非法参数");
        }
		String type = request.getParameter("type");
		if ("publish".equals(type)
				&& !this.dataCheckService.checkCustom(id, "oa_questionnaire", "id", "publish", "0")) {
			return OperationResult.buildFailureResult("没有操作权限");
		}
		if ("close".equals(type) && !this.dataCheckService.checkCustom(id, "oa_questionnaire", "id", "publish", "1")) {
			return OperationResult.buildFailureResult("没有操作权限");
		}
		WebUser user = WebUtils.getCurrentUser();
		Questionnaire questionnaire = questionnaireService.findOne(id);
		//发布时判断问卷是否已经开启
		if(StringUtils.equals(type,"publish") && questionnaire.getPublish() == Questionnaire.PublishEnum.PUBLISH.getCode()){
			i18nKey.put("i18NCode", "oa.que.answerpublished");
			return OperationResult.buildFailureResult("该问卷已经发布");
		}
		//取消发布时判断问卷是否已经关闭
		if(StringUtils.equals(type,"close") && questionnaire.getPublish() == Questionnaire.PublishEnum.NOPUBLISH.getCode()){
			i18nKey.put("i18NCode", "oa.que.answerunpublished");
			return OperationResult.buildFailureResult("该问卷已经取消发布");
		}
		//发布
		if(StringUtils.equals(type,"publish")){
			//发布前清空缓存
			quesCache.del(id+QuestionnaireTopicService.QUES_TYPE);
			quesCache.del(id+QuestionnaireTopicService.QUES_TOPIC);
			quesCache.del(id+QuestionnaireTopicService.QUES_TOPIC_OPT);
			int i = questionnaireService.updateQuesPublish(id,Questionnaire.PublishEnum.PUBLISH.getCode());
			if(i > 0){
				final String quesIdConst=id;
				new Thread(new Runnable() {
					@Override
					public void run() {
						questionnaireService.sendThreadQues(quesIdConst,user.getUserId(),user.getCorpId(),user.getJwtToken(),request);
						
					}},"sendQuestionnaireThread").start();
				i18nKey.put("i18NCode", "oa.que.published");
				return OperationResult.buildSuccessResult("发布成功",i18nKey);
			}
			i18nKey.put("i18NCode", "oa.que.publishedfailure");
			return OperationResult.buildSuccessResult("发布失败",i18nKey);
		}
		//取消发布
		if(StringUtils.equals(type,"close")){
			int i = questionnaireService.stopQuTimingPublish(id, Questionnaire.PublishEnum.NOPUBLISH.getCode(), 0);
			if(i > 0){
				i18nKey.put("i18NCode", "oa.que.operationsuccess");
				return OperationResult.buildSuccessResult("操作成功",i18nKey);
			}
			i18nKey.put("i18NCode", "oa.que.operatedfailure");
			return OperationResult.buildSuccessResult("操作失败",i18nKey);
		}
		i18nKey.put("i18NCode", "oa.que.paramerror");
		return OperationResult.buildFailureResult("参数报错",i18nKey);
	}
	
	/**
     * 获取答案详情列表（翻页）数据
     * 
     * @param request
     * @return json
     */
    @RequestMapping(value = "/answerDetailList", method = RequestMethod.GET)
    @ResponseBody
    public Page<Map> answerDetailList(HttpServletRequest request,
    		@RequestParam("questionnaireId") String questionnaireId,
    		@RequestParam("topicId") String topicId) {
    	Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
		List<PropertyFilter> propertyFilter = PropertyFilter.buildFiltersFromHttpRequest(Questionnaire.class,request);
		Page<Map> page = questionnaireService.answerDetailList(pageable, propertyFilter, questionnaireId, topicId);
		return page;
    }
    
    /**
     * 获取考试类型问卷答卷时间
     * @param request
     * @return
     */
    @RequestMapping(value = "/getExamTime", method = RequestMethod.GET)
    @ResponseBody
    public OperationResult getExamTime(HttpServletRequest request) {
    	Map<String, Object> map = new HashMap<String, Object>();
		String questionnaireId = StringUtils.null2String(request.getParameter("id"));
		if(questionnaireId != null && !ValidateUtils.validateId(questionnaireId)) {
            throw new ValidationException("非法参数");
        }
		Questionnaire ques = this.questionnaireService.findOne(questionnaireId);
		if(ques != null) {
			map.put("createdDate", ques.getCreatedDate());
			map.put("closeDate", ques.getCloseDate());
			map.put("startDate", ques.getStartDate());
			map.put("endDate", ques.getEndDate());
			map.put("noLimit", ques.getNoLimit());
			map.put("answerNum", ques.getAnswerNum());
			map.put("passScore", ques.getPassScore());
		}
		return OperationResult.buildSuccessResult(map);
    }
    
    /**
     * 保存考试类型问卷答卷时间
     * @param request
     * @return
     */
    @RequestMapping(value = "/saveExamTime", method = RequestMethod.POST)
    @ResponseBody
    public OperationResult saveExamTime(HttpServletRequest request) {
    	Map i18nKey=new HashMap(1);
    	try {
    		String questionnaireId = StringUtils.null2String(request.getParameter("questionnaireId"));
			String satrtDate = request.getParameter("startDate");
			String endDate = request.getParameter("endDate");
			String[] examTimeCheck = request.getParameterValues("examTimeCheck");
			Questionnaire ques = this.questionnaireService.findOne(questionnaireId);
			ques.setStartDate(null);
			ques.setEndDate(null);
			ques.setAnswerNum("");
			if(examTimeCheck != null) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				for(String s : examTimeCheck) {
					if("start".equals(s) && StringUtils.isNotBlank(satrtDate))
						ques.setStartDate(sdf.parse(satrtDate));
					if("end".equals(s) && StringUtils.isNotBlank(endDate)) {
						ques.setEndDate(sdf.parse(endDate));
					}
				}
			}
			String noLimit=request.getParameter("noLimit");
			if(StringUtils.isNotEmpty(noLimit)&&"0".equals(noLimit)) {
				String answerNum=request.getParameter("answerNum");
				if(answerNum!=null) {
					//总答题次数
					ques.setAnswerNum(String.valueOf(Integer.valueOf(answerNum)+1));
				}
				
			}
			ques.setNoLimit(noLimit);
			String passScore=request.getParameter("passScore");
			ques.setPassScore(passScore);
			return super.editSave(ques);
		} catch (ParseException e) {
			e.printStackTrace();
			i18nKey.put("i18NCode","oa.que.savefailure");
			return OperationResult.buildFailureResult("保存失败",i18nKey);
		}
    }

}